package vn.com.pavibook.admin.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import vn.com.pavibook.dao.AccountDao;
import vn.com.pavibook.domain.model.Account;
import vn.com.pavibook.utils.DataHelper;

public class UserDetailServiceImpl implements UserDetailsService{
	
	private AccountDao accountDao;
	
	public UserDetailServiceImpl(AccountDao accountDao) {
		this.accountDao = accountDao;
	}
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
		Account accountAdmin = accountDao.getUserByName(username, DataHelper.UserRole.ROLE_FOR_ADMIN.getCode());
		if (accountAdmin != null) {
			AUTHORITIES.add(new SimpleGrantedAuthority(DataHelper.UserRole.ROLE_FOR_ADMIN.getCode()));
			return new User(username, accountAdmin.getPassword(), true,
					true, true, true, AUTHORITIES);
		} else {
			accountAdmin = accountDao.getUserByName(username, DataHelper.UserRole.ROLE_PUBLISHER.getCode());
			if(accountAdmin != null){
				AUTHORITIES.add(new SimpleGrantedAuthority(DataHelper.UserRole.ROLE_PUBLISHER.getCode()));
				return new User(username, accountAdmin.getPassword(), true,
						true, true, true, AUTHORITIES);
			}
			else {
				throw new UsernameNotFoundException("User is authozization!!");
			}
		}
	}


}
